﻿using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using log4net;

namespace Kaleida.ServiceMonitor.Model
{
    public class WebVersionCheck
    {
        private static readonly ILog log = LogManager.GetLogger(typeof (WebVersionCheck));

        private const string VersionCheckUrl = "https://www.rightcalc.com/blog/servicemon/version-check/";

        public VersionCheckResult CheckLatestVersion()
        {
            try
            {
                log.DebugFormat("Checking for latest version of ServiceMon using '{0}'", VersionCheckUrl);

                var request = (HttpWebRequest)WebRequest.Create(VersionCheckUrl);

                var webResponse = request.GetResponse();

                var stream = webResponse.GetResponseStream();
                if (stream == null)
                    throw new InvalidOperationException("Received null response from " + VersionCheckUrl);

                using (var sr = new StreamReader(stream))
                {
                    string html = sr.ReadToEnd();
                    var version = ExtractVersionFromHtmlPage(html);

                    return VersionCheckResult.FoundLatestVersion(version, VersionCheckUrl);
                }
            }
            catch (Exception exception)
            {
                log.ErrorFormat("Error checking for latest version: {0}", exception);
                return VersionCheckResult.Error(exception);
            }
        }

        internal static Version ExtractVersionFromHtmlPage(string html)
        {
            var regex = new Regex("@@@([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)@@@");
            Match match = regex.Match(html);
            if (match.Success)
            {
                var versionString = match.Groups[1].Value;

                Version version;
                if(!Version.TryParse(versionString, out version))
                    throw new InvalidOperationException(string.Format("Cannot parse '{0}' as a Version", versionString));

                return version;
            }
            throw new InvalidOperationException(string.Format("Couldn't extract latest version from {0} page. Unexpected format", VersionCheckUrl));
        }
    }
}
